﻿var ChatYahoo = false;
var ConnectedYahoo = false;
var InfoLoginYahoo = null;
var totalFriendYahoo = 0;
LengthModels["yahoo"] = 0;

function ConnectToYahoo() {
    if (ConnectedYahoo == false) {
        var username = $("#nicknameYahoo").val();
        var password = $("#passwordYahoo").val();
        $('#loading').show();
        var link = "/api/yahoo?username=" + username + "&password=" + password;
        $.ajax({
            url: link,
            dataType: 'json',
            contentType: 'application/json',
            type: "GET",
            success: function (data) {
                InfoLoginYahoo = data;
                rememberConnectToYahoo(username, password);
            },
            error: function (errMsg) {
                $('#loading').hide();
                alert("Kết nối yahoo bị lỗi!");
            }
        });
        DialogConnectYahoo.onCancel();
    }
    else
        alert("bạn đã kết nối thành công tới yahoo messger!")
}
function ConnectToYahooWhenLogin(username, password) {
    if (ConnectedYahoo == false && username != null) {
        $('#loading').show();
        var link = "/api/yahoo?username=" + username + "&password=" + password;
        $.ajax({
            url: link,
            dataType: 'json',
            contentType: 'application/json',
            type: "GET",
            success: function (data) {

                InfoLoginYahoo = data;

                getAllContact();


            },
            error: function (errMsg) {
                $('#loading').hide();
                alert("Kết nối yahoo bị lỗi!");
            }
        });
        DialogConnectYahoo.onCancel();
    }
}
function rememberConnectToYahoo(username, password) {
    var link = "http://localhost:xxxxx/api/account?action=rememberpasswordyahoo&mid=" + Myaccount.ID + "&yusername=" + username + "&ypassword=" + password;
    $.ajax({
        url: link,
        dataType: 'json',
        contentType: 'application/json',
        type: "POST",
        success: function (data) {
            if (data == true) {
                getAllContact();
            }
            else {
                $('#loading').hide();
                alert("Kết nối tới yahoo thất bại!");
                InfoLoginYahoo = null;
            }
        },
        error: function (errMsg) {

            alert("Kết nối yahoo bị lỗi!");
            $('#loading').hide();
            InfoLoginYahoo = null;
        }
    });
}
function getAllContactYahoo() {
    var link = "/api/yahoo?action=contact" +
        "&sid=" + InfoLoginYahoo["sessionId"] +
        "&oauth_token=" + InfoLoginYahoo["oauth_token"] +
        "&oauth_token_secret=" + InfoLoginYahoo["oauth_token_secret"] +
        "&seq=" + seq;
    $.ajax({
        url: link,
        dataType: 'json',
        contentType: 'application/json',
        type: "GET",
        success: function (data) {
            buildModelYahoo(data);
            setSelectedPanelYahoo();
            for (var i = 0 ; i < totalFriendYahoo; i++) {
                Myaccount.UserNameYahoo = $("#nicknameYahoo").val();
                var temp = model[netWork["yahoo"]][i];
                addDivAccountYahoo(netWork["yahoo"] + "_" + i, temp["FullName"], temp["status"]);
                ConnectedYahoo = true;
            };
            refresh();
        },
        complete: function (XMLHttpRequest, textStatus) {
            $('#loading').hide();
        },
        error: function (errMsg) {
            InfoLoginYahoo = null;
            alert("Kết nối yahoo bị lỗi!");
        }
    });
}
function addDivAccountYahoo(id, fullname, status) {
    var divaccount = " <div class=\"account\" id=\"friend" + id + "\" ><img  alt=\"not avatar\" src=\"http://localhost:40000/api/account/" + id + "/avatar\" style =\"width:40px;height:40px;float:left;\"/><img   src=\"/Images/" + liststatus[status] + ".png\" style =\"width:32px;height:32px;float:left;\"/><p>" + fullname + "</p></div>";
    $("#leftColYahoo").append(divaccount);
    $("#friendYahoo" + id).hide();
    $("#friendYahoo" + id).fadeIn(1000);
}
function buildModelYahoo(data) {
    model[netWork["yahoo"]] = [];
    var Contacts = data["contacts"];
    totalFriendYahoo = data["total"];
    for (var i = 0 ; i < totalFriendYahoo; i++) {

        var contact = Contacts[i]["contact"];
        model[netWork["yahoo"]][i] = [];
        model[netWork["yahoo"]][i]["ID"] = contact["id"];
        model[netWork["yahoo"]][i]["FullName"] = cutStringLong(contact["id"], 20);
        var status = contact["presence"]["presenceState"];
        var AoStatus = 0;
        switch (status) {
            case 0:
                AoStatus = 0;
                break;
            case 2:
                AoStatus = 1;
                break;
            case 999:
                AoStatus = 2;
                break;
            case -1:
                AoStatus = 3;
        }

        model[netWork["yahoo"]][i]["status"] = AoStatus;
    };
    LengthModels["yahoo"] = totalFriendYahoo;
}
function SendMessageToServer(myid, contentMessage) {
    if (contentMessage == "")
        return;
    var newid = splitID(currentChat);
    var friendid = model[newid[0]][newid[1]]["ID"];

    var link = "/api/yahoo?action=sendmessage" +
                "&sid=" + InfoLoginYahoo["sessionId"] +
                "&oauth_token=" + InfoLoginYahoo["oauth_token"] +
                "&oauth_token_secret=" + InfoLoginYahoo["oauth_token_secret"] +
                "&fid=" + friendid;
    var messagesend = { Message: contentMessage };
    var stringsend = JSON.stringify(messagesend);
    $.ajax({
        url: link,
        dataType: 'json',
        contentType: 'application/json',
        type: "POST",
        data: stringsend,
        statusCode: {
            //OK
            200: function (data) {
                addMessage(currentChat, Myaccount.FullName, contentMessage);
                var textSend = dom.byId("textSend");
                textSend.value = "";
            },
            //Unauthorized
            401: function () {
                alert('bạn chưa đăng nhập!')
                window.location = "/";
            }
        }
    });
}





var idcurrent = -1;
var model = [];
var netWork = [];
netWork["yahoo"] = 1;
var LengthModels = [];
var seq = 0;
function SendImage(nickname) {

    var img = document.getElementById("currentavatar").src;
    $.ajax({
        url: "http://localhost:40000/api/account/" + nickname + "/avatar",
        contentType: 'image/jpeg',
        type: "POST",
        crossDomain: false,
        data: img,
        success: function (data) {
            document.getElementById('myavatar').src = "http://localhost:40000/api/account/" + Myaccount.ID + "/avatar";
            DialogChangeAvatar.onCancel();
            alert("Thay đổi avatar thành công");
            ChangeAvatar = false;

        },
        error: function (errMsg) {
            alert("Hình ảnh quá lớn không thể làm avatar.Nên chọn dưới 1.5mb");

        }
    });

}